

import 'dart:io';

import 'result_handler.dart';


class SocketHelper{

  static final Map<String, SocketHelper> _cache = <String, SocketHelper>{};
  final String ip;
  final int port;

  factory SocketHelper(String url,int baudRate) {
    return _cache.putIfAbsent(url, () => SocketHelper._internal(url,baudRate));
  }

  SocketHelper._internal(this.ip,this.port){
    open(ip,port);
  }

  ResultHandler resultHandler = ResultHandler();
  Socket? _socket;

  open(ip,port){
    Socket.connect(ip, port,
        timeout: const Duration(seconds: 5))
        .then((socket) async {
          print('$ip connect');
      _socket = socket;

      _socket?.listen(
        onReceivedMsg,
        onError: (e){
          print('onError $e');
          close();
        },
        onDone: (){
          print('onDone');
          close();
        },
        cancelOnError: false,
      );
    }).catchError((error) {
      if (error is SocketException) {
        print(error);
      }
    });
  }

  onReceivedMsg(data) async {
    String hexString = data.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
    print("received=$hexString");
    // Logger().write('received = $hexString\r\n');
    resultHandler.dataReceived(hexString.toUpperCase());
  }

  close(){
    _socket?.close();
    _socket?.destroy();
    _cache.remove(ip);
  }

  sendData(data){
    _socket?.add(data);
  }
}